package com.mingqijia.gassafety.authority.domain;

import com.gap.basic.base.CommonResponse;
import com.gap.filestorage.service.FileStorage;
import com.mingqijia.gassafety.authority.api.req.misc.Message;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.cqrs.MessageEvent;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.message.SendMessageService;
import com.mingqijia.gassafety.shared.handler.GlobalAuthenticationException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 消息发送
 * @author Damon S.
 * @version v0.2
 * @date 2022-03-09 11:13
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MessageProvider implements ApplicationListener<MessageEvent> {

    private final FileStorage fileStorage;
    private final SendMessageService smsService;

    private final Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void onApplicationEvent(MessageEvent event) {
        Message req = (Message) event.getPayload();
        if (ObjectUtils.isEmpty(req)) {
            log.error("错误：不能发送空消息");
            return;
        }
        Map<String, Object> params = new HashMap<>();
        switch (req.getType()) {
            case LOGIN:
                params.put("code", req.getCode());
                break;
            case REGISTER:
                params.put("name", req.getName());
                params.put("ID", req.getUsername());
                params.put("pwd", req.getCode());
                break;
            case RESET_PWD:
                params.put("name", req.getName());
                params.put("Time", format.format(new Date()));
                params.put("pwd", req.getCode());
                break;
            default:
        }
        Map<String, Object> smsPrams = smsService.getRequestParam(req.getPhone(),
                req.getType().getCode(), Constants.ORG_CODE, params, "sms",null,null,null,0);
        try {
            Map<String, Object> res = smsService.sendSms(smsPrams, "");
            if ("false".equals(res.get("result"))) {
                log.error("验证码发送失败[phone={}]", req.getPhone());
            }
        } catch (Exception e) {
            log.error("短信发送失败[phone={}]", req.getPhone(), e);
        }
    }

    /** 上传文件存储 */
    public String uploadStorage(MultipartFile file) throws IOException {
        if (ObjectUtils.isEmpty(file) || file.isEmpty()) {
            throw new GlobalAuthenticationException("上传数据不能为空");
        }
        // 重新生成一个文件名
        String extension = getExtension(
                Objects.requireNonNull(file.getOriginalFilename())
        );
        String fileName = ApplicationUtils.pureUuid().concat(extension);

        ByteArrayInputStream inputStream = new ByteArrayInputStream(file.getBytes());
        CommonResponse response = fileStorage.uploadPrivateFile(fileName, inputStream);
        if (Objects.equals(response.getCode(), Constants.INT_ZERO)) {
            return (String) response.getData();
        }
        throw new GlobalAuthenticationException("上传数据失败");
    }

    /** 上传文件存储 */
    public String uploadImage(MultipartFile file) throws IOException {
        if (ObjectUtils.isEmpty(file) || file.isEmpty()) {
            throw new GlobalAuthenticationException("上传数据不能为空");
        }
        // 重新生成一个文件名
        String extension = getExtension(
                Objects.requireNonNull(file.getOriginalFilename())
        );
        String fileName = ApplicationUtils.pureUuid().concat(extension);

        ByteArrayInputStream inputStream = new ByteArrayInputStream(file.getBytes());
        CommonResponse response = fileStorage.uploadPublicFile(fileName, inputStream);
        if (Objects.equals(response.getCode(), Constants.INT_ZERO)) {
            return (String) response.getData();
        }
        throw new GlobalAuthenticationException("上传数据失败");
    }

    /** 获取图片 */
    public void rebuildStorage(HttpServletResponse response, String fileName) throws IOException {
        try {
            byte[] data = fileStorage.downLoadPrivateFile(fileName);
            ApplicationUtils.writeOutImage(response, data, getExtension(fileName));
        } catch (Exception e) {
            log.error("获取图片[name={}]文件失败", fileName, e);
            ApplicationUtils.writeOutJson(response, CommonResponse.failure(e.getMessage()));
        }
    }

    private String getExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf(Constants.STR_DOT));
    }
}
